package com.colin.aiyi.ui.sayDetail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.colin.aiyi.R;
import com.colin.aiyi.adapter.CommnetAdapter;
import com.colin.aiyi.adapter.OneSayAdapter;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.dao.ImpxUtils3_de.ImpOther;
import com.colin.aiyi.entity.CommentList;
import com.colin.aiyi.entity.SayDetail;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.entity.YiJuAndYiShuoEntity;
import com.colin.aiyi.entity.response.WatchResponse;
import com.colin.aiyi.eventbus.EventCommentist;
import com.colin.aiyi.ui.BaseActivity;
import com.colin.aiyi.ui.CommentListAc;
import com.colin.aiyi.ui.login.LoginAc;
import com.colin.aiyi.ui.pay.PayAc;
import com.colin.aiyi.utils.MusicUtil;
import com.colin.aiyi.utils.TimeUtil;
import com.colin.aiyi.view.ShareBottomDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.shareutil.WXUtil;

/**
 * Created by hl on 2017/5/18.
 */

public class TeacherSayDetailsActivity extends BaseActivity implements IViewDetail {


    @BindView(R.id.text_banner_left)
    TextView textBannerLeft;
    @BindView(R.id.text_banner_title)
    TextView textBannerTitle;
    @BindView(R.id.text_banner_rigth)
    TextView textBannerRigth;
    @BindView(R.id.music_img)
    ImageView musicImg;
    @BindView(R.id.music_title)
    TextView musicTitle;
    @BindView(R.id.music_seekbar)
    SeekBar musicSeekbar;
    @BindView(R.id.music_time)
    TextView musicTime;
    @BindView(R.id.music_play)
    ImageView musicPlay;
    @BindView(R.id.music_time_sum)
    TextView musicTimeSum;
    @BindView(R.id.text_title)
    TextView textTitle;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.text_decs)
    TextView textDecs;
    @BindView(R.id.text_watch)
    TextView textWatch;
    @BindView(R.id.text_like)
    TextView textLike;
    @BindView(R.id.text_reply)
    TextView textReply;
    @BindView(R.id.text_share)
    TextView textShare;
    @BindView(R.id.text_date)
    TextView textDate;
    @BindView(R.id.img_head_pl)
    CircleImageView imgHeadPl;
    @BindView(R.id.text_name_pl)
    TextView textNamePl;
    @BindView(R.id.text_time_pl)
    TextView textTimePl;
    @BindView(R.id.text_decs_pl)
    EditText textDecsPl;
    @BindView(R.id.text_d)
    TextView textD;
    @BindView(R.id.relative)
    RelativeLayout relative;
    @BindView(R.id.button_send)
    Button buttonSend;
    @BindView(R.id.recycler_view_pinglun)
    RecyclerView recyclerViewPinglun;
    @BindView(R.id.text_more)
    TextView textMore;
    @BindView(R.id.recycler_view_recommend)
    RecyclerView recyclerViewRecommend;
    @BindView(R.id.img_small)
    ImageView imgSmall;
    @BindView(R.id.text_music_title)
    TextView textMusicTitle;
    @BindView(R.id.seekbar)
    SeekBar seekbar;
    @BindView(R.id.text_music_time)
    TextView textMusicTime;
    @BindView(R.id.img_play)
    ImageView imgPlay;
    @BindView(R.id.img_play_audio)
    ImageView imgPlayAudio;
    @BindView(R.id.text_music_time_sum)
    TextView textMusicTimeSum;
    RelativeLayout musicRootParent;
    @BindView(R.id.music_play_audio)
    ImageView musicPlayAudio;
    @BindView(R.id.img_big)
    ImageView imgBig;
    private String id = "1";
    private SayDetail sayDetail;
    private String ingUrl;
    private long firstTime;
    private boolean isChildClick=false;
    private Context context;
    ImpPSayDetail iPresenter;
    private ShareBottomDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_details_daoshishuo);
        ButterKnife.bind(this);
        musicRootParent = (RelativeLayout) findViewById(R.id.item_music);
        musicRootParent.setVisibility(View.GONE);
        context = this;
        textBannerTitle.setText("活动详情");
        textBannerLeft.setOnClickListener(this);

        user = getUser();
        if (getIntent() != null) {
            id = getIntent().getStringExtra("id");
            ingUrl = getIntent().getStringExtra("imgurl");
            user.setSayId(id);
        }
//        imgPlayAudio.setVisibility(View.INVISIBLE);
        musicSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                MusicUtil.getInstance().pause(seekBar.getProgress());
            }
        });
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                MusicUtil.getInstance().pause(seekBar.getProgress());
            }
        });
        initUserView(user);
        iPresenter = new ImpPSayDetail();
        iPresenter.setiViewDetail(this);
        musicPlay.setOnClickListener(iPresenter);
    }


    private void initUserView(User user) {
        if (isLogin(user)) {
            Glide.with(this).load(Constant.BASE_URL + user.getHeadUrl()).error(R.mipmap.pic2).into(imgHeadPl);
            textNamePl.setText(user.getUserName());
        }
//        else {
//            relative.setVisibility(View.GONE);
//            buttonSend.setVisibility(View.GONE);
//        }
    }

    @OnClick({ R.id.img_play_audio,R.id.music_play_audio, R.id.text_more, R.id.button_send, R.id.text_share})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.music_play:
                if (isLoginWithLogin(user)) {
                    if (!sayDetail.getData().isFree() || !sayDetail.getData().isIsFree()) {
                        if (!user.isVip()) {
                            showMsg("本条需要VIP请充值");
                            startActivity(new Intent(this, PayAc.class));
                            return;
                        }
                    }
                    if (MusicUtil.getInstance().isPlaying()) {
                        if (isChildClick){
                            MusicUtil.getInstance().pause();
                            MusicUtil.getInstance().sendStartEvent();
                            iPresenter.say_watch(user);
                        }
                        MusicUtil.getInstance().pause();
                    } else {
                        MusicUtil.getInstance().sendStartEvent();
                        iPresenter.say_watch(user);
                    }
                }
                break;
            case R.id.music_play_audio:
            case R.id.img_play_audio:
                MusicUtil.getInstance().stop();
                break;
            case R.id.text_more:
                Intent intent = new Intent(this, CommentListAc.class);
                intent.putExtra("id", id);
                startActivity(intent);
                break;
            case R.id.button_send:
                if (!isLoginWithLogin(user)) {
                    return;
                }
                String content = textDecsPl.getText().toString();
                if (content == null || content.length() < 1) {
                    Toast.makeText(this, "请输入评论内容", Toast.LENGTH_SHORT).show();
                    return;
                }

                //// TODO: 2017/6/22 加反馈
                ImpOther.getInstance().doCommint(id, content);
                textDecsPl.setText("");

                break;
            case R.id.text_share:
                textShare.getCompoundDrawables()[0].setLevel(1);
                if (isLogin(user)) {
                    if (System.currentTimeMillis() - firstTime < 2000) {
                        firstTime = System.currentTimeMillis();
                        break;
                    }
                    if (dialog!=null&&dialog.isVisible()){
                        return;
                    }
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            dialog = new ShareBottomDialog();
                            dialog.setUrl(Constant.SAY_getDetail + id);
                            dialog.setTitle(sayDetail.getData().getTitle());
                            dialog.setBitmap(WXUtil.getBitmap(Constant.BASE_URL + sayDetail.getData().getUrl()));
                            dialog.show(getSupportFragmentManager());
                        }
                    }.start();

                } else {
                    Intent intent2 = new Intent(this, LoginAc.class);
                    startActivity(intent2);
                }

                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        iPresenter.say_getDetail(user);
        iPresenter.say_commentList(user);
    }

    /*观看事件，音频正式播放的前置条件*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkWatch(WatchResponse response) {
        if (response.getCode() == 200) {
            MusicUtil.getInstance().setDataSource(this, sayDetail.getData().getVoiceUrl() + response.getData().getToken());
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(SayDetail say) {
        if (say.getCode() == 200) {
            this.sayDetail = say;  //赋值供点击时使用
            bindView(sayDetail);//绑定数据
        } else {
            showMsg(say.getMessage());
            finish();
        }

    }

    /*评论结果集*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventCommentist sayDatail) {
        CommentList commentList = sayDatail.getCommentList();
        bindViewComment(commentList);
    }

    /* 绑定评论*/
    private void bindViewComment(CommentList commentList) {
        CommnetAdapter headerAndFooterAdapter = new CommnetAdapter(commentList.getData().getItems());
        recyclerViewPinglun.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewPinglun.setAdapter(headerAndFooterAdapter);
    }

    /****
     * 绑定导师说详情
     * @param sayDetail
     */
    private void bindView(SayDetail sayDetail) {

        Glide.with(this).load(Constant.BASE_URL + sayDetail.getData().getUrl()).error(R.mipmap.pic1).into(musicImg);
        Glide.with(this).load(Constant.BASE_URL + sayDetail.getData().getUrl()).error(R.mipmap.pic1).into(imgBig);
        textTitle.setText(sayDetail.getData().getTitle());
        textDecs.setText(sayDetail.getData().getContent());
        textDate.setVisibility(View.INVISIBLE);
        textTime.setText("更新时间：" + TimeUtil.getTime(sayDetail.getData().getCreatedDate(), TimeUtil.DATE_FORMAT_DATE_YEAR_M__D_DOT));
        textWatch.setText(sayDetail.getData().getWatchCount() + "");
        textLike.setText(sayDetail.getData().getLikeCount() + "");
        textReply.setText(sayDetail.getData().getCommentCount() + "");
        textShare.setVisibility(View.VISIBLE);
        textShare.getCompoundDrawables()[0].setLevel(1);
        textMusicTitle.setText(sayDetail.getData().getTitle());
        bindRecommend(sayDetail);//
//        MusicUtil.getInstance().setMusicTitle(sayDetail.getData().getTitle());
//        MusicUtil.getInstance().setMusicPic(Constant.BASE_URL + sayDetail.getData().getUrl());
    }

    private void bindPingLun(SayDetail sayDetail) {
//        PingLunAdapter headerAndFooterAdapter = new PingLunAdapter(sayDetail.getData().getRecommendList());
//        recyclerViewPinglun.setLayoutManager(new LinearLayoutManager(this));
//        recyclerViewPinglun.setAdapter(headerAndFooterAdapter);
    }

    /*******
     * 绑定推荐
     * @param sayDetail
     */
    private void bindRecommend(SayDetail sayDetail) {
        OneSayAdapter headerAndFooterAdapter = new OneSayAdapter(sayDetail.getData().getRecommendList(), this);
        recyclerViewRecommend.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewRecommend.setAdapter(headerAndFooterAdapter);
        headerAndFooterAdapter.setOnItemChildClickListener(iPresenter);
//        headerAndFooterAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//
//                YiJuAndYiShuoEntity childYiShuoEntity = (YiJuAndYiShuoEntity) adapter.getData().get(position);
//                MusicUtil.getInstance().setMusicTitle(childYiShuoEntity.getTitle());
//                MusicUtil.getInstance().setMusicPic(Constant.BASE_URL + childYiShuoEntity.getUrl());
//                if (isLoginWithLogin(user)) {
//                    if (!childYiShuoEntity.isFree() || !childYiShuoEntity.isIsFree()) {
//                        if (!user.isVip()) {
//                            showMsg("本条需要VIP请充值");
//                            startActivity(new Intent(context, PayAc.class));
//                            return;
//                        }
//                    }
//                    if (MusicUtil.getInstance().isPlaying()) {
//                        MusicUtil.getInstance().stop();
//                    } else {
//                        User user = SharePreferenceUtil.getObject(context, User.class);
//                        user.setSayId(childYiShuoEntity.getId() + "");
//                        iPresenter.say_watch(user);
//                    }
//                }
//              //  MusicUtil.getInstance().sendStopEvent();
//                isChildClick = true;
//                MusicUtil.getInstance().sendStartEvent();
//            }
//        });
        headerAndFooterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(TeacherSayDetailsActivity.this, TeacherSayDetailsActivity.class);
                String id = ((YiJuAndYiShuoEntity) adapter.getData().get(position)).getId() + "";
                intent.putExtra("id", id);
                startActivity(intent);
                finish();
            }
        });

    }

    /*音频事件*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateMusicEvent(MusicUtil.MuiscEvent muiscEvent) {
        if (isChildClick) {
            doMusicChildEvent(muiscEvent);
        } else {
            musicRootParent.setVisibility(View.GONE);
            doMusicLocalEvent(muiscEvent);
        }

    }

    /********
     * 处理详情音频事件
     * @param muiscEvent
     */
    private void doMusicLocalEvent(MusicUtil.MuiscEvent muiscEvent) {
        String musicpic = MusicUtil.getInstance().getMusicPic();
        String musicpic2 = Constant.BASE_URL + sayDetail.getData().getUrl();
        if (!musicpic.equals(musicpic2)) {
            return;
        }
        switch (muiscEvent.getEventType()) {
            case MusicUtil.MEDIA_STATUS_START:
                Glide.with(this).load(MusicUtil.getInstance().getMusicPic()).error(R.mipmap.pic1).into(musicImg);
                musicTitle.setText("正在缓冲...");
                musicTime.setText("0:00");
                musicTimeSum.setText("0:00");
                musicSeekbar.setMax(100);
                musicSeekbar.setProgress(0);
                musicPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_PREPARE:
            case MusicUtil.MEDIA_STATUS_PLAY:
                musicTitle.setText(MusicUtil.getInstance().getMusicTitle());
                try {
                    musicTime.setText(MusicUtil.getMusicTime(muiscEvent.getMediaPlayer().getCurrentPosition()));
                } catch (Exception e) {
                    e.printStackTrace();
                    musicTime.setText("0:00");
                }
                try {
                    musicTimeSum.setText(MusicUtil.getMusicTime(muiscEvent.getMediaPlayer().getDuration()));
                } catch (Exception e) {
                    e.printStackTrace();
                    musicTimeSum.setText("0:00");
                }
                musicSeekbar.setMax(muiscEvent.getMediaPlayer().getDuration());
                musicSeekbar.setProgress(muiscEvent.getMediaPlayer().getCurrentPosition());
                musicPlay.getBackground().setLevel(1);
                break;
            case MusicUtil.MEDIA_STATUS_PAUSE:
                musicPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_STOP:
                musicTime.setText("0:00");
                musicSeekbar.setProgress(0);
                musicPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_COMLETION:
                musicSeekbar.setProgress(0);
                musicPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_EEROR:
                musicPlay.getBackground().setLevel(0);
                showMsg("声音地址异常");
                break;

        }
    }


    /*处理列表音频播放事件*/
    private void doMusicChildEvent(MusicUtil.MuiscEvent muiscEvent) {
        if (isChildClick) {  //false 说明不是当前列表的，列表音频事件，隐藏音频控件不做处理，
            musicRootParent.setVisibility(View.VISIBLE);
        } else {
            musicRootParent.setVisibility(View.GONE);
        }
        switch (muiscEvent.getEventType()) {
            case MusicUtil.MEDIA_STATUS_START:
                Glide.with(this).load(MusicUtil.getInstance().getMusicPic()).error(R.mipmap.pic1).into(imgSmall);
                textMusicTitle.setText("正在缓冲...");
                textMusicTime.setText("0:00");
                textMusicTimeSum.setText("0:00");
                seekbar.setMax(100);
                seekbar.setProgress(0);
                imgPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_PREPARE:
            case MusicUtil.MEDIA_STATUS_PLAY:
                textMusicTitle.setText(MusicUtil.getInstance().getMusicTitle());
                try {
                    textMusicTime.setText(MusicUtil.getMusicTime(muiscEvent.getMediaPlayer().getCurrentPosition()));
                } catch (Exception e) {
                    e.printStackTrace();
                    textMusicTime.setText("0:00");
                }
                try {
                    textMusicTimeSum.setText(MusicUtil.getMusicTime(muiscEvent.getMediaPlayer().getDuration()));
                } catch (Exception e) {
                    e.printStackTrace();
                    textMusicTimeSum.setText("0:00");
                }
                seekbar.setMax(muiscEvent.getMediaPlayer().getDuration());
                seekbar.setProgress(muiscEvent.getMediaPlayer().getCurrentPosition());
                imgPlay.getBackground().setLevel(1);
                break;
            case MusicUtil.MEDIA_STATUS_PAUSE:
                imgPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_STOP:
                textMusicTitle.setText(MusicUtil.getInstance().getMusicTitle());
                textMusicTime.setText("0:00");
                seekbar.setProgress(0);
                imgPlay.getBackground().setLevel(0);
                isChildClick = false;
            case MusicUtil.MEDIA_STATUS_COMLETION:
                seekbar.setProgress(0);
                imgPlay.getBackground().setLevel(0);
                isChildClick = false;
                break;
            case MusicUtil.MEDIA_STATUS_EEROR:
                imgPlay.getBackground().setLevel(0);
                showMsg("声音地址异常");
                isChildClick = false;
                break;

        }
    }


    @Override
    public boolean checkUserVip() {
        if (!user.isVip()) {
            showMsg("本条需要VIP请充值");
            startActivity(new Intent(context, PayAc.class));
            return false;
        }
        return true;
    }

    @Override
    public boolean checkLogin() {
        if (!isLoginWithLogin(user)){
            showMsg("本条需要VIP请充值");
            startActivity(new Intent(context, PayAc.class));
            return false;
        }
        return true;
    }

    @Override
    public String  getId() {
        return id;
    }

    @Override
    public boolean isChildClick() {
        return isChildClick;
    }

    @Override
    public void setChildClick(boolean blo) {
        isChildClick=blo;
    }

}
